<!DOCTYPE html>
<html lang="en"
      xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<div th:replace="common/common::html"></div>
<head>
    <meta charset="UTF-8">
    <title th:text="#{role.page.title}"></title>
    <link th:href="@{/assets/css/page.css}" rel="stylesheet"/>
    <script th:inline="javascript">
        var _gridWidth;
        var _gridHeight;

        //页面自适应
        function resizePageSize() {
            _gridWidth = $(document).width() - 12;/*  -189 是去掉左侧 菜单的宽度，   -12 是防止浏览器缩小页面 出现滚动条 恢复页面时  折行的问题 */
            _gridHeight = $(document).height() - 65 - 40; /* -32 顶部主菜单高度，   -90 查询条件高度*/
        }

        $(function () {
            resizePageSize();
            var _columnWidth = (_gridWidth - 150) / 3;
            $("#flexigrid-id").flexigrid({
                width: _gridWidth,
                height: _gridHeight,
                url: /*[[@{/role/queryRoleInfoListByPage}]]*/"",
                dataType: 'json',
                colModel: [
                    {display: 'roleUuid', name: 'roleUuid', width: 150, sortable: false, align: 'center', hide: 'true'},
                    {
                        display: /*[[#{role.name}]]*/"",
                        name: 'roleName',
                        width: _columnWidth,
                        sortable: true,
                        align: 'center'
                    },
                    {
                        display: /*[[#{role.remarks}]]*/"",
                        name: 'remarks',
                        width: _columnWidth,
                        sortable: true,
                        align: 'center'
                    },
                    {
                        display: /*[[#{common.operation}]]*/"",
                        name: 'roleUuid',
                        width: _columnWidth,
                        sortable: true,
                        align: 'center',
                        process: function (v, trid, _row) {
                            var html = `<div>`
                            if ([[${#authorization.expression("hasRole('ROLE_cldk_data_role_mod')")}]]) {
                                html += `<a href="#" class="btn" onclick="modifyRoleInfo('${v}')" title=[[#{commom.modify}]]><i class="glyphicon glyphicon-pencil"></i></a>`
                            }
                            if ([[${#authorization.expression("hasRole('ROLE_cldk_data_role_del')")}]]) {
                                html += `<a href="#" class="btn" onclick="deleteRoleInfo('${v}','${_row.roleName}')" title=[[#{commom.delete}]]><i class="glyphicon glyphicon-trash"></i></a>`
                            }
                            if ([[${#authorization.expression("hasRole('ROLE_cldk_data_role_menu')")}]]) {
                                html += `<a href="#" class="btn" onclick="allocatePermission('${v}')" title=[[#{role.allocate.permission}]]><i class="glyphicon glyphicon-share"></i></a>`
                            }
                            if ([[${#authorization.expression("hasRole('ROLE_cldk_data_role_view')")}]]) {
                                html += `<a href="#" class="btn" onclick="viewRoleUsers('${v}')" title=[[#{role.view.users}]]><i class="glyphicon glyphicon-option-horizontal"></i></a>`
                            }
                            html += `<div>`
                            return html;

                        }
                    },
                ],
                resizable: false, //resizable table是否可伸缩
                useRp: true,
                usepager: true, //是否分页
                autoload: false, //自动加载，即第一次发起ajax请求
                hideOnSubmit: true, //是否在回调时显示遮盖
                showcheckbox: true, //是否显示多选框
                rowhandler: rowDbclick, //是否启用行的扩展事情功能,在生成行时绑定事件，如双击，右键等
                rowbinddata: true
            });

            // 初始化用户表格
            $("#view-users-table-id").flexigrid({
                width: 760,  // 适配800px宽度的对话框
                height: 400, // 适配500px高度的对话框
                url: "",     // 初始不加载数据，查看时动态设置
                dataType: 'json',
                colModel: [
                    {
                        display: 'userUuid',
                        name: 'userUuid',
                        width: 100,
                        sortable: false,
                        align: 'center',
                        hide: true  // 隐藏UUID列，仅用于内部处理
                    },
                    {
                        display: /*[[#{user.account}]]*/'',
                        name: 'userAccount',
                        width: 120,
                        sortable: true,
                        align: 'center'
                    },
                    {
                        display: /*[[#{user.name}]]*/'',
                        name: 'userName',
                        width: 100,
                        sortable: true,
                        align: 'center'
                    },
                    {
                        display: /*[[#{user.dept}]]*/'',
                        name: 'deptName',
                        width: 120,
                        sortable: true,
                        align: 'center'
                    },
                    {
                        display: /*[[#{user.post}]]*/'',
                        name: 'postName',
                        width: 120,
                        sortable: true,
                        align: 'center'
                    },
                    {
                        display: /*[[#{user.status}]]*/'',
                        name: 'status',
                        width: 100,
                        sortable: true,
                        align: 'center',
                        process: function(v) {
                            // 状态格式化：1=启用(绿色)，0=禁用(红色)
                            if (v === '1') {
                                return `<span class="label label-success">[[#{common.enable}]]</span>`;
                            } else {
                                return `<span class="label label-danger">[[#{common.disable}]]</span>`;
                            }
                        }
                    },
                    {
                        display: /*[[#{user.join.date}]]*/'',
                        name: 'joinDate',
                        width: 120,
                        sortable: true,
                        align: 'center'
                    }
                ],
                // 分页配置
                useRp: true,          // 启用分页
                rp: 10,               // 每页默认10条
                rpOptions: [5, 10, 20], // 可选每页条数
                usepager: true,       // 显示分页控件
                // 其他配置
                resizable: false,     // 禁止列宽调整
                autoload: false,      // 不自动加载数据
                hideOnSubmit: true,   // 提交时显示加载遮罩
                showcheckbox: false,  // 不显示复选框
                singleSelect: true,   // 单选模式
                title: /*[[#{role.related.users}]]*/'', // 表格标题
                // 排序配置
                sortname: "joinDate", // 默认排序字段
                sortorder: "desc",    // 默认排序方向
                // 回调函数
                onSuccess: function() {
                    // 数据加载成功后的处理
                    $(this).find('tr:even').addClass('even-row');
                },
                onError: function() {
                    message(/*[[#{common.data.load.error}]]*/'');
                }
            });




            query()
            /**
             * 修改角色对话框
             */
            $("#modify-role-dialog-id").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                resizable: false,
                title: /*[[#{role.modify.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function () {
                            var flag = $("form#modify-role-form-id input.form-control").checkDom()
                            if (!flag) {
                                return
                            }
                            $("#modify-role-form-id").submit()
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function () {
                            $(this).dialog("close");
                        }
                    }//end buttons
                ]
            })//end dialog

            /**
             * 修改角色异步表单
             */
            $("#modify-role-form-id").ajaxForm({
                dataType: "json",
                success: function (data) {
                    message(data.msg);
                    query();
                    if (data.success) {
                        $("#modify-role-dialog-id").dialog('close')
                    }
                },
                error: function () {
                    message(/*[[#{common.error}]]*/'');
                }

            })//end ajaxForm

            /**
             * 增加角色对话框
             */
            $("#add-role-dialog-id").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                resizable: false,
                title: /*[[#{role.add.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function () {
                            var flag = $("form#add-role-form-id input.form-control").checkDom()
                            if (!flag) {
                                return
                            }
                            $("#add-role-form-id").submit()
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function () {
                            $(this).dialog("close");
                        }
                    }//end buttons
                ]
            })

            /**
             * 增加角色异步表单
             */
            $("#add-role-form-id").ajaxForm({
                dataType: "json",
                success: function (data) {
                    message(data.msg);
                    query();
                    if (data.success) {
                        $("#add-role-dialog-id").dialog('close')
                    }
                },
                error: function () {
                    message(/*[[#{common.error}]]*/'');
                }

            })//end ajaxForm

            //删除角色对话框
            $("#delete-role-dialog-id").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                resizable: false,
                title: /*[[#{role.delete.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function () {
                            var ids = $("#delete-role-dialog-id").attr("ids")
                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType: 'json',
                                url: /*[[@{/role/deleteRoleByIds}]]*/'',
                                data: [{name: "ids", value: ids}],
                                success: function (data) {
                                    // console.info('deleteRoleByIds；' + JSON.stringify(data))
                                    message(data.msg)
                                    if (data.success) {
                                        $("#delete-role-dialog-id").dialog('close')
                                        query()
                                    }

                                },
                                error: function (msg) {
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });

                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function () {
                            $(this).dialog("close");
                        }
                    }//end buttons
                ]
            });

            //分配权限对话框
            $("#allocate-permission-dialog-id").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                resizable: false,
                title: /*[[#{role.allocate.permission.dialog}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function () {
                            let roleUuidArray = $("#allocate-permission-dialog-id").attr('ids')
                            let menuIdArray = []
                            let treeObj = $.fn.zTree.getZTreeObj("allocate-permission-ztree-id")
                            let nodes = treeObj.getCheckedNodes(true)
                            $(nodes).each(function (index, item) {
                                menuIdArray.push(item.id)
                            })
                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType: 'json',
                                url: /*[[@{/role/saveRoleRefMenu}]]*/'',
                                data: [
                                    {name: "menuIdArray", value: menuIdArray},
                                    {name: "roleUuidArray", value: roleUuidArray},
                                ],
                                success: function (data) {
                                    message(data.msg)
                                    if (data.success) {
                                        $("#allocate-permission-dialog-id").dialog(`close`)
                                    }

                                },
                                error: function (msg) {
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });

                        }

                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function () {
                            $(this).dialog("close");
                        }
                    }//end buttons
                ]
            })

            // 初始化查看用户对话框（新增）
            $("#view-users-dialog").dialog({
                autoOpen: false,
                width: 800,
                height: 500,
                modal: true,
                resizable: false,
                buttons: [
                    {
                        text: /*[[#{common.close}]]*/'',
                        click: function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            });


        })//end ready function

        function query() {
            var roleName = $("#role-name-id").val()
            $("#flexigrid-id").flexOptions({
                extParam: [
                    {name: "roleName", value: roleName},
                ]
            }).flexReload()
        }

        //双击事件
        function rowDbclick(r) {
            $(r).dblclick(
                function () {
                    var columnsArray = $(r).attr('ch').split("_FG$SP_");
                    // console.info(columnsArray);
                    var roleUuid = columnsArray[0]

                    modifyRoleInfo(roleUuid);
                });
        }


        /**
         * 修改角色信息
         * @param roleUuid
         */
        function modifyRoleInfo(roleUuid) {
            $.ajax({
                    type: 'post',
                    async: false,
                    dataType: 'json',
                    url: /*[[@{/role/queryRoleInfoById}]]*/'',
                    data: [{name: "roleUuid", value: roleUuid}],
                    success: function (data) {

                        var list = $("form#modify-role-form-id input.form-control");
                        list.each(function (index, item) {
                            var name = $(item).attr("name")
                            $(this).val(data[name])

                        })
                        $("form#modify-role-form-id input.form-control").checkDom()

                        $("#modify-role-dialog-id").dialog('open')
                    },
                    error: function (msg) {
                        message(/*[[#{common.error}]]*/'');
                    }
                }
            );
        }

        //增加角色
        function addRole() {
            $("form#add-role-form-id input.form-control").removeClass('ui-state-error');
            $("#add-role-form-id").resetForm();
            $("#add-role-dialog-id").dialog('open')
        }//end add role


        //删除角色
        function bathDeleteRole() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if (ids.length === 0) {
                message(/*[[#{common.empty}]]*/);
                return;
            }

            $("#delete-role-dialog-id").attr('ids', ids)

            // console.info("bathDeleteUser idx:" + JSON.stringify(ids))
            var niceNameArray = $("#flexigrid-id").getFlexigridiAttrByIndex(1)
            $("#delete-role-list-id").text(niceNameArray.join(","))

            $("#delete-role-dialog-id").dialog('open')
        }

        //单独删除角色
        function deleteRoleInfo(roleUuid, roleName) {
            $("#delete-role-dialog-id").attr('ids', roleUuid)
            $("#delete-role-list-id").text(roleName)

            $("#delete-role-dialog-id").dialog('open')
        }


        var allocateSetting = {
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            }
        };

        //批量分配权限
        function bathAllocatePermission() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if (ids.length === 0) {
                message(/*[[#{common.empty}]]*/);
                return;
            }

            allocatePermission(ids)

        }

        //分配权限
        function allocatePermission(roleUuid) {
            $("#allocate-permission-dialog-id").attr('ids', roleUuid)
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/role/queryMenuTreeListByRole}]]*/'',
                data: [{name: "roleUuid", value: roleUuid}],
                success: function (data) {
                    $.fn.zTree.init($('#allocate-permission-ztree-id'), allocateSetting, data)

                    $("#allocate-permission-dialog-id").dialog('open')

                },
                error: function (msg) {
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }


        /**
         * 查看角色关联的用户
         * @param roleUuid 角色UUID
         */
        function viewRoleUsers(roleUuid) {
            // 设置表格的URL，用于加载指定角色的用户数据
            $("#view-users-table-id").flexOptions({
                url: /*[[@{/role/queryUsersByRole}]]*/'',
                extParam: [
                    {name: "roleUuid", value: roleUuid}
                ]
            }).flexReload();

            // 打开对话框
            $("#view-users-dialog").dialog('open');
        }



    </script>

</head>
<body>

<header>
    <input id="role-name-id" th:placeholder="#{role.name.plc}">


    <a href="#" class="btn-info btn" onclick="query()">
        <i class="glyphicon glyphicon-search"></i>
        <span th:text="#{common.query}"></span>
    </a>

    <a href="#" sec:authorize="hasRole('ROLE_cldk_data_role_add')" class="btn-info btn" onclick="addRole()">
        <i class="glyphicon glyphicon-plus"></i>
        <span th:text="#{common.add}"></span>
    </a>

    <a href="#" sec:authorize="hasRole('ROLE_cldk_data_role_del')" class="btn-info btn" onclick="bathDeleteRole()">
        <i class="glyphicon glyphicon-trash"></i>
        <span th:text="#{common.delete}"></span>
    </a>

    <a href="#" sec:authorize="hasRole('ROLE_cldk_data_role_menu')" class="btn-info btn"
       onclick="bathAllocatePermission()">
        <i class="glyphicon glyphicon-share"></i>
        <span th:text="#{role.allocate.permission}"></span>
    </a>


</header>
<table id="flexigrid-id"></table>


<div id="modify-role-dialog-id" sec:authorize="hasRole('ROLE_cldk_data_role_mod')" style="...">
    <form id="modify-role-form-id" method="post" th:action="@{/role/modifyRoleInfoById}">
        <div class="form-group">
            <span th:text="#{role.uuid}"></span>
            <input class="form-control" name="roleUuid" readonly>
        </div>

        <div class="form-group">
            <span th:text="#{role.name}"></span>
            <input class="form-control" name="roleName" pattern="^.{4,}$">
        </div>

        <div class="form-group">
            <span th:text="#{role.remarks}"></span>
            <input class="form-control" name="remarks"
                   pattern="^.*$">
        </div>

    </form>

</div>


<div id="add-role-dialog-id" sec:authorize="hasRole('ROLE_cldk_data_role_add')" style="...">
    <form id="add-role-form-id" method="post" th:action="@{/role/addRoleInfoById}">

        <div class="form-group">
            <span th:text="#{role.name}"></span>
            <input class="form-control" name="roleName"
                   th:placeholder="#{role.name.plc}"
                   pattern="^.{4,}$">
        </div>

        <div class="form-group">
            <span th:text="#{role.remarks}"></span>
            <input class="form-control" name="remarks"
                   th:placeholder="#{role.remarks.plc}"
                   pattern="^.*$">
        </div>

    </form>

</div>

<div id="delete-role-dialog-id" sec:authorize="hasRole('ROLE_cldk_data_role_del')" style="display: none">
    <span id="delete-role-list-id"></span>
</div>

<div id="allocate-permission-dialog-id" sec:authorize="hasRole('ROLE_cldk_data_role_menu')" style="display: none">
    <ul id="allocate-permission-ztree-id" class="ztree"></ul>
</div>

<div id="view-users-dialog" sec:authorize="hasRole('ROLE_cldk_data_role_view')" style="display: none;">
    <table id="view-users-table-id"></table>
</div>


</body>
</html>
